package metu.tespit.session.authentication;


import java.security.MessageDigest;

import javax.persistence.EntityManager;

import metu.tespit.entitiy.accountManagement.User;
import metu.tespit.entitiy.accountManagement.UserRole;
import metu.tespit.session.sessionScopeManager.SessionScopeBean;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesContext;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.util.Base64;

@Name("authenticator")
public class Authenticator
{
	@Logger private Log log;
	@In Identity identity;
	@In Credentials credentials;
	@In EntityManager entityManager;
	@In SessionScopeBean sessionScopeBean;

	public boolean authenticate()
	{
		log.info("authenticating {0}", credentials.getUsername());
		
		
		try {
			
			User user = (User) entityManager.createQuery("select u from User u where u.username = :username and u.password= :pass")
			.setParameter("username", credentials.getUsername()).setParameter("pass", getHash(credentials.getPassword(), "C47t1TuP6=4159W")).getSingleResult();
			if(user.getUserRoles() != null){
				for(UserRole role: user.getUserRoles()){
					identity.addRole(role.getRoleName());
				}
			}
			else{
				log.info("authentication Failed For {0}!!", credentials.getUsername());
				return false;
			}
			
			//sadece student rolu var ise
			if(user.isStudent() && user.getUserRoles().size() == 1){
				// aktif degilse giris yapamasin
				if(!user.aktifSemesterdaKursuVarMi()){
					FacesMessages.instance().add("User has no active courses in current semester");
					return false;
				}
			}

			return true;
		} catch (Exception e) {
			return false;
		}

	}


	private String getHash(String password,String saltPhrase)throws Exception{
		MessageDigest md = MessageDigest.getInstance("MD5");

		md.update(saltPhrase.getBytes());

		byte[] salt = md.digest();


		md.reset();

		md.update(password.getBytes("UTF-8"));

		md.update(salt);


		byte[] raw = md.digest();



		return new String(Base64.encodeBytes(raw));
	}


}
